<template>
  <div class="app">
    <a-breadcrumb style="margin-bottom: 10px">
      <a-breadcrumb-item>综治组织/ 综治队伍人员</a-breadcrumb-item>
    </a-breadcrumb>
    <a-row class="pd20 mt20">
      <a-col :span="6">
        人员姓名：
        <a-input placeholder="请输入" v-model="queryForm.name" />
      </a-col>
      <a-col :span="6">
        队伍类型：
        <a-select v-model="queryForm.type">
          <a-select-option
            :value="item.id"
            v-for="item in organizationList"
            :key="item.id"
          >
            {{ item.teamName }}
          </a-select-option>
        </a-select>
      </a-col>
      <a-col :span="6">
        手机号码：
        <a-input placeholder="请输入" v-model="queryForm.phone" />
      </a-col>
      <a-col :span="6">
        身份证号码：
        <a-input placeholder="请输入" v-model="queryForm.idNumber" />
      </a-col>
      <a-col :span="6">
        所属民族：
        <a-input placeholder="请输入" v-model="queryForm.nationality" />
      </a-col>
      <a-col :span="6">
        职务名称：
        <a-input placeholder="请输入" v-model="queryForm.job" />
      </a-col>
      <a-col :span="9">
        创建时间范围：
        <a-range-picker
          style="width: 330px; margin-left: 10px"
          v-model="dateRange"
          :placeholder="['开始日期', '结束日期']"
          valueFormat="YYYY-MM-DD HH:mm:ss"
          :show-time="{
            hideDisabledOptions: true,
            defaultValue: [
              moment('00:00:00', 'HH:mm:ss'),
              moment('23:59:59', 'HH:mm:ss'),
            ],
          }"
          format="YYYY-MM-DD HH:mm:ss"
          @change="onChange"
        />
      </a-col>
      <a-col :span="3">
        <a-button type="primary" @click="getList"> 查询 </a-button>&emsp;&nbsp;
        <a-button @click="reset">重置</a-button>
      </a-col>
    </a-row>
    <a-row class="pd20 mt20">
      <div class="flex-between mb10">
        <div class="flex-start">
          <a-button
            type="primary"
            @click="addFn"
            v-hasPermi="['zhonghe:zzdw:import']"
            >导入</a-button
          >
          <a-button
            type="primary"
            @click="addFn"
            v-hasPermi="['zhonghe:zzdw:export']"
            >导出</a-button
          >
        </div>
        <div class="flex-end">
          <a-button
            type="primary"
            @click="addFn"
            v-hasPermi="['zhonghe:zzdw:add']"
            >添加</a-button
          >
          <a-button
            v-if="false"
            type="danger"
            @click="delFn"
            v-hasPermi="['zhonghe:zzdw:del']"
            >删除</a-button
          >
        </div>
      </div>
      <a-spin :spinning="loading">
        <a-table
          :scroll="{ x: 1200 }"
          :columns="columns"
          :data-source="tableData"
          :pagination="false"
          style="overflow-x: auto"
          :row-key="(record) => record.id"
        >
          <template slot="idNumer" slot-scope="text, record">
            <div class="phone-cell">
              <span>{{
                record.showIdNumer ? text : $maskChineseIdCard(text)
              }}</span>
              <a-icon
                :type="record.showIdNumer ? 'eye-invisible' : 'eye'"
                @click.stop="toggleIdNumberVisibility2(record)"
              />
            </div>
          </template>
          <template slot="phone" slot-scope="text, record">
            <div class="phone-cell">
              <span>{{
                record.showPhone ? text : $desensitizePhone(text)
              }}</span>
              <a-icon
                :type="record.showPhone ? 'eye-invisible' : 'eye'"
                @click.stop="togglePhoneVisibility(record)"
              />
            </div>
          </template>
          <span slot="status" slot-scope="text, record">
            <a-switch
              :checked="record.status === 0"
              @change="(checked) => onStatusChange(checked, record)"
            />
          </span>
          <span slot="action" slot-scope="text, record">
            <a @click="handleView(record)" v-hasPermi="['zhonghe:zzdw:view']"
              >查看</a
            >
            <a-divider type="vertical" />
            <a @click="editFn(record)" v-hasPermi="['zhonghe:zzdw:edit']"
              >修改</a
            >
            <a-divider type="vertical" />
            <a
              @click="delFn(record)"
              class="red"
              v-hasPermi="['zhonghe:zzdw:del']"
              >删除</a
            >
          </span>
        </a-table>
        <div class="page_box">
          <a-pagination
            v-model="queryForm.offset"
            :page-size-options="['20', '30', '40', '50']"
            :total="total"
            show-size-changer
            :page-size="queryForm.current"
            @showSizeChange="onShowSizeChange"
            @change="pageChange"
            :show-total="(total) => `共 ${total} 条`"
          ></a-pagination>
        </div>
      </a-spin>
    </a-row>
    <a-modal
      :title="title"
      :visible="dialogVisible"
      width="30%"
      @cancel="dialogVisible = false"
    >
      <a-form
        :form="form"
        :label-col="{ span: 5 }"
        :wrapper-col="{ span: 19 }"
        style="height: 550px; overflow-y: auto"
      >
        <a-form-item label="姓名">
          <template v-if="type === 'View'">
            {{ currentRecord.name }}
          </template>
          <a-input
            v-else
            style="width: 100%"
            v-decorator="[
              'name',
              {
                rules: [{ required: true, message: '请输入姓名' }],
              },
            ]"
            placeholder="请输入姓名"
          />
        </a-form-item>
        <a-form-item label="性别">
          <template v-if="type === 'View'">
            {{ currentRecord.gender }}
          </template>
          <a-select
            v-else
            style="width: 100%"
            v-decorator="[
              'gender',
              {
                rules: [{ required: true, message: '请选择性别' }],
              },
            ]"
            placeholder="请选择性别"
          >
            <a-select-option
              v-for="item in genderList"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="政治面貌">
          <template v-if="type === 'View'">
            {{ currentRecord.governmentStatus }}
          </template>
          <a-select
            v-else
            style="width: 100%"
            v-decorator="[
              'governmentStatus',
              {
                rules: [{ required: true, message: '请选择政治面貌' }],
              },
            ]"
            placeholder="请选择政治面貌"
          >
            <a-select-option
              v-for="item in governmentStatusList"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="队伍类型">
          <template v-if="type === 'View'">
            {{ currentRecord.type }}
          </template>
          <a-select
            v-else
            style="width: 100%"
            v-decorator="[
              'type',
              {
                rules: [{ required: true, message: '请选择队伍类型' }],
              },
            ]"
            placeholder="请选择队伍类型"
          >
            <a-select-option
              v-for="item in organizationList"
              :key="item.id"
              :value="item.id"
            >
              {{ item.teamName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="学历">
          <template v-if="type === 'View'">
            {{ currentRecord.education }}
          </template>
          <a-select
            v-else
            style="width: 100%"
            v-decorator="[
              'education',
              {
                rules: [{ required: true, message: '请选择学历' }],
              },
            ]"
            placeholder="请选择学历"
          >
            <a-select-option
              v-for="item in educationList"
              :key="item.value"
              :value="item.value"
            >
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="民族">
          <template v-if="type === 'View'">
            {{ currentRecord.nationality }}
          </template>
          <a-input
            v-else
            style="width: 100%"
            v-decorator="[
              'nationality',
              {
                rules: [{ required: true, message: '请输入民族' }],
              },
            ]"
            placeholder="请输入民族"
          />
        </a-form-item>
        <a-form-item label="联系方式">
          <template v-if="type === 'View'">
            {{ currentRecord.phone }}
          </template>
          <a-input
            v-else
            style="width: 100%"
            v-decorator="[
              'phone',
              {
                rules: [{ required: true, message: '请输入联系方式' }],
              },
            ]"
            placeholder="请输入联系方式"
          />
        </a-form-item>
        <a-form-item label="职务">
          <template v-if="type === 'View'">
            {{ currentRecord.job }}
          </template>
          <a-input
            v-else
            style="width: 100%"
            v-decorator="[
              'job',
              {
                rules: [{ required: true, message: '请输入职务' }],
              },
            ]"
            placeholder="请输入职务"
          />
        </a-form-item>
        <a-form-item label="身份证号码">
          <template v-if="type === 'View'">
            {{ currentRecord.idNumer }}
          </template>
          <a-input
            v-else
            style="width: 100%"
            @change="handleIdCardChange"
            v-decorator="[
              'idNumer',
              {
                rules: [{ required: true, message: '请输入身份证号码' }],
              },
            ]"
            placeholder="请输入身份证号码"
          />
        </a-form-item>

        <a-form-item label="出生日期">
          <template v-if="type === 'View'">
            {{ currentRecord.bornDate }}
          </template>
          <a-date-picker
            v-else
            style="width: 100%"
            disabled
            valueFormat="YYYY-MM-DD"
            v-decorator="[
              'bornDate',
              {
                rules: [{ required: true, message: '请输入出生日期' }],
              },
            ]"
            placeholder="请输入出生日期"
          />
        </a-form-item>

        <a-form-item label="年龄">
          <template v-if="type === 'View'">
            {{ currentRecord.age }}
          </template>
          <a-input
            v-else
            style="width: 100%"
            disabled
            v-decorator="[
              'age',
              {
                rules: [{ required: true, message: '请输入年龄' }],
              },
            ]"
            placeholder="请输入年龄"
          />
        </a-form-item>

        <a-form-item label="所属机构">
          <template v-if="type === 'View'">
            {{
              orgList.find(
                (item) =>
                  item.id === currentRecord.organizationMassDefenceDetailId
              ).teamName
            }}
          </template>
          <a-select
            v-else
            style="width: 100%"
            v-decorator="[
              'organizationMassDefenceDetailId',
              {
                rules: [{ required: false }],
              },
            ]"
            placeholder="请选择所属机构"
          >
            <a-select-option
              v-for="item in orgList"
              :key="item.id"
              :value="item.id"
            >
              {{ item.teamName }}
            </a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
      <template slot="footer">
        <BtnFooter
          :loading="submitLoading"
          :isShowOk="type !== 'View'"
          @cancel="dialogVisible = false"
          @ok="handleSubmit"
        />
      </template>
    </a-modal>
  </div>
</template>

<script>
import crudMixin from "@/mixins/crudMixin";
import { genderList, educationList, governmentStatusList } from "./form";
import BtnFooter from "@/component/btnFooter.vue";
export default {
  mixins: [crudMixin],
  components: {
    BtnFooter,
  },
  data() {
    return {
      genderList: genderList,
      educationList: educationList,
      governmentStatusList: governmentStatusList,
      organizationList: [
        {
          id: 0,
          teamName: "综治",
        },
        {
          id: 1,
          teamName: "群防群治",
        },
      ],
      orgList: [],
      dateRange: [],
      // 请求配置 - 这里定义每个操作的请求格式
      requestConfig: {
        Add: {
          method: "post",
          type: "formData", // 新增请求使用 formData 格式
          url: "/government-platform-center/organizationMassDefenceStaff",
        },
        Edit: {
          method: "post",
          type: "formData", // 修改请求使用 JSON 格式
          url: "/government-platform-center/organizationMassDefenceStaff/edit",
        },
        Del: {
          method: "post",
          type: "formData", // 删除请求使用 formData 格式
          url: "/government-platform-center/organizationMassDefenceStaff/deleteById",
        },
        Detail: {
          method: "get",
          type: "json",
          url: "",
        },
        Get: {
          method: "get",
          type: "json",
          url: "/government-platform-center/organizationMassDefenceStaff",
        },
      },
      // 模态框配置
      modalConfig: {
        addTitle: "新增队伍人员信息",
        editTitle: "修改队伍人员信息",
        viewTitle: "查看队伍人员信息",
        deleteConfirm: "确定要删除该队伍人员信息吗？删除后不可恢复！",
      },

      // 表单对象
      form: this.$form.createForm(this, { name: "coordinated" }),

      // 列配置
      columns: [
        {
          title: "人员ID",
          dataIndex: "id",
          key: "id",
        },
        {
          title: "人员姓名",
          dataIndex: "name",
          key: "name",
        },
        {
          title: "人员性别",
          dataIndex: "gender",
          key: "gender",
          customRender: (text, record) => {
            return this.genderList.find((item) => item.value === record.gender)
              .label;
          },
        },
        {
          title: "民族",
          dataIndex: "nationality",
          key: "nationality",
        },
        {
          title: "所属机构",
          dataIndex: "Name",
          key: "Name",
          customRender: (text, record) => {
            let findOne = this.orgList.find(
              (item) => item.id === record.organizationMassDefenceDetailId
            );
            return (findOne && findOne.teamName) || "";
          },
        },
        {
          title: "队伍类型",
          dataIndex: "type",
          key: "type",
          customRender: (text, record) => {
            let findOne = this.organizationList.find(
              (item) => item.id === record.type
            );
            return (findOne && findOne.teamName) || "";
          },
        },
        {
          title: "联系方式",
          dataIndex: "phone",
          key: "phone",
          scopedSlots: { customRender: "phone" },
          width: 150,
        },
        {
          title: "身份证号码",
          dataIndex: "idNumer",
          key: "idNumer",
          scopedSlots: { customRender: "idNumer" },
          width: 170,
        },
        {
          title: "出生年月",
          dataIndex: "bornDate",
          key: "bornDate",
        },
        {
          title: "年龄",
          dataIndex: "age",
          key: "age",
          customRender: (text, record) => {
            let age = this.getAge(record.idNumer);
            return age || "";
          },
        },
        {
          title: "政治面貌",
          dataIndex: "governmentStatus",
          key: "governmentStatus",
          customRender: (text, record) => {
            return this.governmentStatusList.find(
              (item) => item.value === record.governmentStatus
            ).label;
          },
        },
        {
          title: "学历",
          dataIndex: "education",
          key: "education",
          customRender: (text, record) => {
            return this.educationList.find(
              (item) => item.value === record.education
            ).label;
          },
        },
        {
          title: "职务",
          dataIndex: "job",
          key: "job",
        },
        {
          title: "最近更新时间",
          dataIndex: "updateTime",
          key: "updateTime",
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          key: "createTime",
        },
        {
          title: "操作",
          key: "action",
          width: 160,
          scopedSlots: { customRender: "action" },
        },
      ],
    };
  },

  methods: {
    // 处理身份证号码变更，自动提取出生日期和年龄
    handleIdCardChange(e) {
      const idCard = e.target.value;
      if (idCard && idCard.length === 18) {
        try {
          // 提取出生日期 格式为YYYYMMDD
          const year = idCard.substring(6, 10);
          const month = idCard.substring(10, 12);
          const day = idCard.substring(12, 14);

          // 格式化出生日期
          const birthDate = `${year}-${month}-${day}`;

          // 计算年龄，使用现有的getAge方法
          const age = this.getAge(idCard);

          // 设置表单值
          this.form.setFieldsValue({
            bornDate: birthDate,
            age: age,
          });
        } catch (error) {
          console.error("解析身份证日期出错:", error);
        }
      }
    },
    // 计算年龄
    getAge(idCard) {
      if (!idCard) return "";
      const year = idCard.substring(6, 10);
      const month = idCard.substring(10, 12);
      const day = idCard.substring(12, 14);
      const now = new Date();
      const birthDate = new Date(year, month - 1, day);
      let age = now.getFullYear() - birthDate.getFullYear();
      const monthDiff = now.getMonth() - birthDate.getMonth();
      if (
        monthDiff < 0 ||
        (monthDiff === 0 && now.getDate() < birthDate.getDate())
      ) {
        age--;
      }
      return age;
    },
    onChangePushTime(date, dateString) {
      this.queryForm.pushTime = dateString;
    },
    formatAddData(data = {}) {
      return {
        status: 0,
        ...data,
      };
    },
    addFn() {
      this.add();
    },
    handleView(val) {
      let data = {
        ...val,
        age: this.getAge(val.idNumer),
      };
      this.view(data);
    },
    editFn(val) {
      let data = {
        ...val,
        age: this.getAge(val.idNumer),
      };
      this.edit(data);
    },
    delFn(val) {
      this.del(val);
    },
    // 处理状态改变
    onStatusChange(checked, record) {
      const url = "/government-platform-center/organization/updateStatus";
      const params = {
        id: record.id,
        status: checked ? 1 : 0, // 转换为后端需要的数字类型
      };

      this.$axios
        .post(url, params)
        .then((res) => {
          if (res.data.code === 0) {
            this.$message.success("状态修改成功");
            this.getList();
          } else {
            this.$message.error(res.data.msg || "操作失败");
          }
        })
        .catch((err) => {
          console.error("状态更新错误:", err);
          this.$message.error("操作失败");
        });
    },
    reset() {
      this.dateRange = [];
      this.cleanQuery();
    },
    // 处理日期范围变化
    onChange(dates, dateStrings) {
      if (dates) {
        this.queryForm.startTime = dateStrings[0];
        this.queryForm.endTime = dateStrings[1];
      } else {
        this.queryForm.startTime = null;
        this.queryForm.endTime = null;
      }
    },
    // 获取所属机构
    getOrganizationList() {
      this.$axios
        .get(
          "/government-platform-center/organizationTeam/?current=1000&offset=1"
        )
        .then((res) => {
          this.orgList = res.data.data || [];
        })
        .catch((err) => {
          console.error("获取所属机构失败:", err);
        });
    },
    togglePhoneVisibility(record) {
      this.$set(record, "showPhone", !record.showPhone);
    },
    toggleIdNumberVisibility2(record) {
      this.$set(record, "showIdNumer", !record.showIdNumer);
    },
  },

  mounted() {
    this.getList();
    this.getOrganizationList();
  },
};
</script>

<style lang="scss" scoped>
.ant-row {
  border-radius: 5px;
  background: #fff;
  color: #000;
}

v-deep {
  .ant-table-thead > tr > th {
    color: #000;
    font-weight: bold;
  }
  .ant-table-tbody > tr > td {
    color: #000;
  }
  .el-table thead {
    color: black;
    font-weight: bold;
    background: #fafafa;
  }
  .el-table th.el-table__cell {
    background: #fafafa;
  }
}

.ant-col {
  margin: 10px 0;
}

.ant-select {
  width: 60%;
}

.ant-input {
  width: 60%;
}

@media screen and (max-width: 1300px) {
  .el-input {
    width: 70%;
  }

  .el-select {
    width: 70%;
  }

  .app {
    width: calc(100% - 50px);
  }
}

@media screen and (max-width: 1100px) {
  .el-input {
    width: 90%;
  }

  .el-select {
    width: 90%;
  }
}
.img {
  width: 50px;
  height: 50px;
}
.btn_box {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
}
.flex-between {
  display: flex;
  justify-content: space-between;
}
.flex-start {
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}
.flex-end {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
